package com.hongtech.framework.interceptor;

import com.hongtech.common.bean.Token;
import com.hongtech.common.util.TokenUtil;
import com.hongtech.framework.anno.Permission;
import com.hongtech.modules.system.service.PermissionService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 资源拦截器
 */
@Component
public class PermissionInterceptor implements HandlerInterceptor {

    @Autowired
    private PermissionService permissionService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
            Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Token token = TokenUtil.getToken(request);
            Permission permissionSecurity = handlerMethod.getMethodAnnotation(Permission.class);
            if (permissionSecurity != null) {
                if (permissionService.hasPermission(token, permissionSecurity.value())) {
                    return true;
                }
                request.setAttribute("url", request.getRequestURL());
                request.getRequestDispatcher("/error/403").forward(request, response);
                return false;
            }
        }
        return true;
    }

}
